<template>
  <div class="app-container">
    <el-row :gutter="30">
      <el-col :span="8">
        <div class="p-2">
          <el-table :data="identityData">
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column label="部门名称" prop="deptName"></el-table-column>
            <el-table-column label="用户姓名" prop="nickName"></el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  v-if="scope.row.userId !== props.userInfo.userId"
                  type="primary"
                  size="small"
                  link
                  @click="delBindUserId(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="16" class="border-l-solid border-l-1 border-gray-300">
        <el-row :gutter="20">
          <!--部门数据-->
          <el-col :span="7" :xs="24">
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                prefix-icon="Search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                :data="deptOptions"
                :props="{ label: 'label', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="deptTreeRef"
                node-key="id"
                highlight-current
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-col>
          <!--用户数据-->
          <el-col :span="17" :xs="24">
            <el-form
              :model="queryParams"
              ref="queryRef"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
              @submit.prevent
              ><el-row>
                <!--                <el-col :span="12">-->
                <!--                  <el-form-item label="登录账号" prop="userName">-->
                <!--                    <el-input-->
                <!--                      v-model="queryParams.userName"-->
                <!--                      placeholder="请输入登录账号"-->
                <!--                      clearable-->
                <!--                      style="width: 240px"-->
                <!--                      @keyup.enter="handleQuery"-->
                <!--                    />-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
                <el-col :span="12">
                  <el-form-item label="用户姓名" prop="nickName">
                    <el-input
                      v-model="queryParams.nickName"
                      placeholder="请输入用户实名"
                      clearable
                      style="width: 240px"
                      @change="handleQuery($event)"
                    />
                  </el-form-item>
                </el-col>
                <!--                <el-col :span="12">-->
                <!--                  <el-form-item label="状态" prop="status">-->
                <!--                    <el-select-->
                <!--                      v-model="queryParams.status"-->
                <!--                      placeholder="用户状态"-->
                <!--                      clearable-->
                <!--                      style="width: 240px"-->
                <!--                    >-->
                <!--                      <el-option-->
                <!--                        v-for="dict in sys_normal_disable"-->
                <!--                        :key="dict.value"-->
                <!--                        :label="dict.label"-->
                <!--                        :value="dict.value"-->
                <!--                      />-->
                <!--                    </el-select>-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
                <!--                <el-col :span="12">-->
                <!--                  <el-form-item label="创建时间" style="width: 308px">-->
                <!--                    <el-date-picker-->
                <!--                      v-model="dateRange"-->
                <!--                      value-format="YYYY-MM-DD"-->
                <!--                      type="daterange"-->
                <!--                      range-separator="-"-->
                <!--                      start-placeholder="开始日期"-->
                <!--                      end-placeholder="结束日期"-->
                <!--                    ></el-date-picker>-->
                <!--                  </el-form-item>-->
                <!--                </el-col>-->
                <el-col :span="12">
                  <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery"
                      >搜索</el-button
                    >
                    <el-button icon="Refresh" @click="resetQuery"
                      >重置</el-button
                    >
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-table
              v-loading="loading"
              :data="userList"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                type="index"
                label="序号"
                width="50"
                align="center"
              />
              <el-table-column
                label="部门"
                align="center"
                v-if="columns[1].visible"
                :show-overflow-tooltip="true"
              >
                <template #default="scope">
                  <span>{{
                    scope.row.dept != null ? scope.row.dept.deptName : '-'
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="用户姓名"
                align="center"
                key="nickName"
                prop="nickName"
                v-if="columns[2].visible"
                :show-overflow-tooltip="true"
              />
              <el-table-column
                label="状态"
                align="center"
                key="status"
                v-if="columns[5].visible"
              >
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.status"
                    active-value="0"
                    inactive-value="1"
                    disabled
                    @change="handleStatusChange(scope.row)"
                  ></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="80">
                <template #default="scope">
                  <el-button
                    link
                    size="small"
                    type="primary"
                    @click="addIdentity(scope.row)"
                    >添加</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Identity">
import { getToken } from '@/utils/auth'
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  getUserIdentityList
} from '@/api/system/user'
import { treeselect } from '@/api/system/dept'
import { getCurrentInstance, reactive, ref, toRefs, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getConfigKey } from '@/api/system/config'
import {
  limitUserList,
  limitUserInsert,
  limitUserDelete
} from '@/api/system/dict/data'

const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  'sys_normal_disable',
  'sys_user_sex'
)

const userList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const dateRange = ref([])
const deptName = ref('')
const deptOptions = ref(undefined)
const drawer = ref(false)
// 身份名称
const identityName = ref('')
const props = defineProps({
  userInfo: {
    type: Object,
    default: () => {
      return {}
    }
  },
  objId: {
    type: String || Number
  },
  tableName: {
    type: String
  }
})

// 列显隐信息
const columns = ref([
  { key: 0, label: '用户编号', visible: true },
  { key: 1, label: '用户名称', visible: true },
  { key: 2, label: '用户昵称', visible: true },
  { key: 3, label: '部门', visible: true },
  { key: 4, label: '手机号码', visible: true },
  { key: 5, label: '状态', visible: true },
  { key: 6, label: '创建时间', visible: true }
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined
  },
  identityData: [],
  userDetails: '',
  roleIds: ''
})

const { queryParams, form, identityData, userDetails, roleIds } = toRefs(data)

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}
/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs['deptTreeRef'].filter(val)
})

/**
 * 初始化，获取当前用户的身份列表
 */
async function init() {
  if (props.objId || props.objId === 0) {
    await limitUserList({
      objId: props.objId,
      tableName: props.tableName
    }).then(res => {
      console.log(res, 'objId')
      identityData.value = res.data
    })
  } else {
    let userName = toRaw(props.userInfo).userName
    await getUserIdentityList(userName).then(res => {
      identityData.value = res.data
    })
  }
  let userId = toRaw(props.userInfo).userId
  await getUser(userId).then(res => {
    userDetails.value = res.data
    roleIds.value = res.roleIds
  })
}

/**
 * 添加身份
 * @param row 表格行数据
 */
function addIdentity(row) {
  let user = userDetails.value
  let userIds = user.bindUserIds.split(',')
  if (userIds.includes(row.userId.toString())) {
    proxy.$modal.msgWarning('已有该身份，请勿重复添加')
    return
  }
  userIds.push(row.userId)
  let bindUserIds = userIds.join(',')
  user.roleIds = roleIds.value
  user.bindUserIds = bindUserIds
  if (props.objId || props.objId === 0) {
    const params = {
      objId: props.objId,
      tableName: props.tableName,
      nickName: row.nickName,
      deptName: row.dept.deptName,
      userId: row.userId
    }
    limitUserInsert(params).then(res => {
      init()
    })
  } else {
    updateUser(user).then(res => {
      init()
    })
  }
}

/**
 * 删除绑定的身份id
 * @param row
 */
function delBindUserId(row) {
  let user = userDetails.value
  let userIds = user.bindUserIds.split(',')
  let bindUserIds = userIds.filter(item => {
    return item !== row.userId.toString()
  })
  let bindUserIdsStr = bindUserIds.join(',')
  user.roleIds = roleIds.value
  user.bindUserIds = bindUserIdsStr
  if (props.objId || props.objId === 0) {
    limitUserDelete(row.id).then(res => {
      init()
    })
  } else {
    // 修改角色
    updateUser(user).then(res => {
      init()
    })
  }
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  treeselect().then(response => {
    deptOptions.value = response.data
  })
}

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false
    userList.value = res.rows
    total.value = res.total
  })
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  handleQuery()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm('queryRef')
  queryParams.value.deptId = undefined
  proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.userId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

getDeptTree()
getList()
init()
</script>
<style scoped lang="scss"></style>
